package com.zklh.leetcode.interviewTop150;


import com.zklh.leetcode.tree.model.Node;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 填充每个节点下一个右侧节点指针II
 */
public class Solution117 {
    public Node connect(Node root) {
        Queue<Node> queue = new LinkedList<>();
        if (root == null) {
            return null;
        }
        queue.add(root);

        Node tempNode = new Node(1);
        while (!queue.isEmpty()) {
            int currentTierSize = queue.size();
            Node prev = tempNode;
            for (int i = 0; i < currentTierSize; i++) {
                prev.next = queue.poll();
                if (prev.next.left != null) {
                    queue.add(prev.next.left);
                }
                if (prev.next.right != null) {
                    queue.add(prev.next.right);
                }
                prev = prev.next;
            }
        }
        return root;
    }
}
